package com.powerbank.ordercenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.powerbank.ordercenter.entity.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单Mapper接口
 */
@Mapper
public interface OrderMapper extends BaseMapper<Order> {

    /**
     * 根据用户ID查询活跃订单
     */
    @Select("SELECT * FROM orders WHERE user_id = #{userId} AND order_status IN ('CREATED', 'PAID', 'USING') AND deleted = 0")
    List<Order> findActiveOrdersByUserId(@Param("userId") Long userId);

    /**
     * 根据设备ID查询当前订单
     */
    @Select("SELECT * FROM orders WHERE device_id = #{deviceId} AND order_status IN ('PAID', 'USING') AND deleted = 0 LIMIT 1")
    Order findCurrentOrderByDeviceId(@Param("deviceId") Long deviceId);

    /**
     * 查询超时未归还订单
     */
    @Select("SELECT * FROM orders WHERE order_status = 'USING' AND planned_return_time < #{currentTime} AND deleted = 0")
    List<Order> findOverdueOrders(@Param("currentTime") LocalDateTime currentTime);

    /**
     * 查询超时未支付订单
     */
    @Select("SELECT * FROM orders WHERE order_status = 'CREATED' AND created_time < #{expireTime} AND deleted = 0")
    List<Order> findUnpaidExpiredOrders(@Param("expireTime") LocalDateTime expireTime);

    /**
     * 根据订单号查询订单
     */
    @Select("SELECT * FROM orders WHERE order_no = #{orderNo} AND deleted = 0")
    Order findByOrderNo(@Param("orderNo") String orderNo);

    /**
     * 统计用户订单数量
     */
    @Select("SELECT COUNT(*) FROM orders WHERE user_id = #{userId} AND deleted = 0")
    Integer countOrdersByUserId(@Param("userId") Long userId);

    /**
     * 统计设备使用次数
     */
    @Select("SELECT COUNT(*) FROM orders WHERE device_id = #{deviceId} AND order_status IN ('COMPLETED', 'RETURNED') AND deleted = 0")
    Integer countCompletedOrdersByDeviceId(@Param("deviceId") Long deviceId);
}